package com.sparrow.common.msghandler;

import com.sparrow.common.thread.ThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class MessageHandler<H extends IMessageHandler<?>> implements Runnable, IMessageHandler<H> {

    private static Logger logger = LoggerFactory.getLogger(MessageHandler.class);

    private static final int THREAD_COUNT = Runtime.getRuntime().availableProcessors() * 2;


    private Queue<IMessage> queue = new ConcurrentLinkedQueue<>();

    private AtomicInteger size = new AtomicInteger(0);

    private volatile Thread thread;

    public void addMessage(IMessage<H> message) {
        queue.add(message);
        int size = this.size.incrementAndGet();
        if (size == 1) {
            ThreadPool.SCENE_EXECUTOR.execute(this);
        }
    }

    @Override
    public void run() {
        while (true) {
            IMessage message = queue.poll();
            if (message == null) {
                break;
            }
            thread = Thread.currentThread();
            message.run(this);
            int size = this.size.decrementAndGet();
            if (size == 0) {
                thread = null;
                break;
            }
        }
    }

    public boolean inThread() {
        return thread != null && Thread.currentThread() == thread;
    }


}
